package naga.x.net.filter;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;

import naga.x.App;
import naga.x.common.Config;

public class ConnectionsFilter extends IoFilterAdapter {
	
	private AtomicInteger counter = new AtomicInteger();
	private Config config = App.getApp().getConfig();
	
	public static Object sessionCloseMessage; // 连接数超过最大限制时提示消息

	@Override
	public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
		int n = counter.incrementAndGet();
		if (config.maxConnections > 0 && n > config.maxConnections) {
			Object msg = sessionCloseMessage;
			if (msg != null) {
				session.write(msg);
			}
			session.closeOnFlush();
			return;
		}
		super.sessionCreated(nextFilter, session);
	}

//	@Override
//	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
//		super.sessionOpened(nextFilter, session);
//	}

	@Override
	public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
		counter.decrementAndGet();
		super.sessionClosed(nextFilter, session);
	}
	
	
}
